function demoObj1() {
    const obj = {};

    let gender;
    Object.defineProperty(obj, "gender", {
        get() {
            console.log("get");
            return gender;
        },
        set(value) {
            console.log("set", value);
            gender = value;
        },
    });

    obj.gender = "male";
    console.log(obj.gender);
    console.log(obj);
}
// demoObj1()

function demoObj2() {
    const map = {
        name: "黑哥",
        age: 18,
    };

    const obj = {};
    for (let key in map) {
        Object.defineProperty(obj, key, {
            set(value) {
                console.log("set", key, value);
                map[key] = value;
            },
            get() {
                console.log("get", key);
                return map[key];
            },
        });
    }

    obj.name = "白鸽";
    console.log(obj.name);
    obj.age = 28;
    console.log(obj.age);
}
// demoObj2()

/* 无法监听delete操作 */
/* 无法监听对新的key的操作 */
function demoObj3() {
    const map = {
        name: "黑哥",
        age: 18,
    };

    const arr = {};
    for (let key in map) {
        Object.defineProperty(arr, key, {
            set(value) {
                console.log("set", key, value);
                map[key] = value;
            },
            get() {
                console.log("get", key);
                return map[key];
            },
        });
    }

    delete arr.name;
    console.log(arr.name);

    // 监听不到
    arr.hobby = "撸码";
}
// demoObj3()

/* 对数组不友好 */
function demoArr() {
    function defineReactive(obj, key, val) {
        Object.defineProperty(obj, key, {
            get() {
                console.log(`get ${key}:${val}`);
                return val;
            },
            set(newVal) {
                console.log(`get ${key}:${newVal}`);
                if (newVal !== val) {
                    val = newVal;
                }
            },
        });
    }

    const arrData = [1, 2, 3, 4, 5];
    arrData.forEach((val, index) => {
        defineReactive(arrData, index, val);
    });

    arrData.push(6); // no ok
    arrData.pop(); // no ok
    arrData[0] = 99; // ok
}
// demoArr();

/* 数据劫持强化 */
function fn(){
    const data = {}
    Object.defineProperty(data,"age",{
        get(){
            return data.x_age
        },

        // data.age = 19
        set(newValue){
            console.log("set",newValue);

            // 依然触发set(newValue) 堕入递归死循环
            // data.age = newValue

            // 要刻意将数据存储到别的地方去
            // data.age的数据真身在data.x_age中
            // data.age“纯粹”作为一个劫持监听之用（专业人质）
            data.x_age = newValue
        }

    })

    // 访问data.age 会触发get()
    console.log(data.age);

    // 这行代码会触发set(19)
    data.age = 19//这里对data.age的操作并不会真的形成data.age 而是被劫持走了
    console.log("data.age",data.age);
    console.log("data",data);
}
// fn()
